/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package com.dhpollack.rotogss.servlets;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dhpollack.rotogss.data.AppConfig;
import com.dhpollack.rotogss.helper.AppHelper;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;

/**
 * @author davidpl
 *
 */
public class GoogleOAuthStartServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2467815349841892123L;

	protected void service(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
				
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if (user != null) {
        	
        	AppConfig appConfig = AppHelper.get();
        	
    		GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
    		oauthParameters.setOAuthConsumerKey(appConfig.getGoogleConsumerKey());
    		oauthParameters.setOAuthConsumerSecret(appConfig.getGoogleConsumerSecret());
    		oauthParameters.setScope("https://docs.google.com/feeds/ https://spreadsheets.google.com/feeds/");

    		GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());

    	    try {
    			oauthHelper.getUnauthorizedRequestToken(oauthParameters);

    			String oauth_token_secret = oauthParameters.getOAuthTokenSecret();
    			StringBuilder stringBuilder = new StringBuilder();
    			stringBuilder.append(appConfig.getBaseUrl());
    			stringBuilder.append("/googleauthreturn");
    			stringBuilder.append("?oauth_token_secret=");
    			stringBuilder.append(URLEncoder.encode(oauth_token_secret,"UTF-8"));
    			oauthParameters.setOAuthCallback(stringBuilder.toString());

    			String requestUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);

    			log("OAuth Token Secret: " + oauth_token_secret);
    			log("Request URL: " + requestUrl);
    			
    			resp.sendRedirect(requestUrl);
    			

    		} catch (OAuthException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        } else {
            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        }
	}

}
